import wiringpi as gpio
import sys

dpin = 12
cpin = 11

gpio.wiringPiSetupPhys()
gpio.pinMode(cpin, gpio.OUTPUT)
gpio.pinMode(dpin, gpio.OUTPUT)

clk_flag = False

def send_16bit_data(data):
	for i in range(16):
		if data&0x8000:
			gpio.digitalWrite(dpin, gpio.HIGH)
		else:
			gpio.digitalWrite(dpin, gpio.LOW)
		global clk_flag
		if clk_flag:
			gpio.digitalWrite(cpin, gpio.LOW)
			clk_flag = False
		else:
			gpio.digitalWrite(cpin, gpio.HIGH)
			clk_flag = True
		gpio.delayMicroseconds(500)
		data = data << 1


def latch_data():
	latch_flag = False
	gpio.digitalWrite(dpin, gpio.LOW)
	gpio.delayMicroseconds(500)
	for i in range(8):
		if latch_flag:
			gpio.digitalWrite(dpin, gpio.LOW)
			latch_flag = 0
		else:
			gpio.digitalWrite(dpin, gpio.HIGH)
			latch_flag = 1
	gpio.delayMicroseconds(500)

def send_led(state):
	for i in range(12):
		if state&1:
			send_16bit_data(0xff)
		else:
			send_16bit_data(0)
		state = state >> 1


if __name__ == '__main__':
	try:
		for i in range(0b10000000000):
			send_16bit_data(0)
			send_led(i)
			latch_data()
	except KeyboardInterrupt:
		send_16bit_data(0)
		send_led(0)
		latch_data()
		gpio.delay(200)
